// pages/detail/detail.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const audio = wx.createInnerAudioContext({
  useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //歌曲id
    musicId: null,
    //歌曲src
    musicUrl: null,
    //底部图标 暂停1 单曲循环5 随机播放8
    iconData: [
      {
        icon: '../../images/icon_a0idh5lo91/icon-_6.png',
        singleIcon: '../../images/icon_a0idh5lo91/icon-_5.png',
        randomIcon: '../../images/icon_a0idh5lo91/icon-_8.png',
      },
      {
        icon: '../../images/icon_a0idh5lo91/icon-_3.png'
      },
      {
        icon: '../../images/icon_a0idh5lo91/icon-_4.png',
        pauseIcon: '../../images/icon_a0idh5lo91/icon-_1.png',
      },
      {
        icon: '../../images/icon_a0idh5lo91/icon-_2.png'
      },
      {
        icon: '../../images/icon_a0idh5lo91/icon-.png'
      },
    ],
    //播放状态
    isPlay: false,
    //播放模式:0位列表循环,1为单曲循环,2为随机播放
    playMode: 0,
    //总时长
    totalTime: '00:00',
    duration: null,
    //当前时间
    currentTime: '00:00',
    //滑块的值
    sliderValue: 0,
    //歌词数组
    lyricArr: [],
    //歌词高亮下标
    highLightIndex: 0,
    //获取歌词辅助状态
    getWords: false,
    //所有歌词高度
    wordsHeight: [],
    //定时器
    timer: null,
    //滚动距离
    top: 0,
    //初始化高度
    iniHeight: 0,
    //播放列表弹出层
    popupShow: false,
    //播放列表歌曲
    songsList: [],
    //列表播放歌曲下标
    playIndex: null,
  },

  //时间格式处理
  formarSongsTime(duration) {
    let minute = Math.floor(duration / 60)
    let second = Math.floor(duration % 60)
    minute = minute < 10 ? `0${minute}` : (minute + '')
    second = second < 10 ? `0${second}` : (second + '')
    return minute + ':' + second
  },

  //播放器
  playControl(e) {
    let index = e.currentTarget.dataset.index
    if (index == 2) {
      let isPlay = this.data.isPlay
      isPlay = !isPlay
      this.setData({
        isPlay: isPlay
      })
      if (isPlay) {
        audio.play()
      } else {
        audio.pause()
      }
    } else if (index == 0) {
      let playMode = this.data.playMode
      if (playMode == 0) {
        playMode = 1
        Toast({
          message: '单曲循环',
          position: 'bottom'
        });
      } else if (playMode == 1) {
        playMode = 2
        Toast({
          message: '随机播放',
          position: 'bottom'
        });
      } else if (playMode == 2) {
        playMode = 0
        Toast({
          message: '顺序播放',
          position: 'bottom'
        });
      }
      this.setData({
        playMode: playMode
      })
    } else if (index == 4) {
      this.setData({ popupShow: true });
    } else if (index == 1) {
      this.setData({
        getWords: false
      })
      this.playModeChangeSongs(index)
    } else if (index == 3) {
      this.setData({
        getWords: false
      })
      this.playModeChangeSongs(index)
    }
  },

  //拖动进度条更改当前播放时间
  dropToChange(e) {
    let sliderValue = e.detail.value
    this.setData({
      sliderValue,
      isPlay: true
    })
    let newTime = (sliderValue / 100) * this.data.duration
    audio.seek(newTime)
    audio.play()
  },

  //拖动时暂停
  dropToChange2(e) {
    audio.pause()
    let currentTime = (e.detail.value / 100) * this.data.duration
    currentTime = this.formarSongsTime(currentTime)
    this.setData({
      isPlay: false,
      currentTime
    })
  },

  //获取歌词
  getSongWords() {
    this.setData({
      lyricArr: [],
      wordsHeight: []
    })
    wx.request({
      // url: 'http://localhost:3000/lyric?id=21273745',
      url: `http://localhost:3000/lyric?id=${this.data.songsList[this.data.playIndex].id}`,
      success: res => {
        // console.log(res.data.lrc.lyric);//英文
        // console.log(res.data.tlyric.lyric);//中文
        if (res.data.lrc.lyric) {
          //判断有没有歌词，因为有些音乐没有歌词
          let arr = res.data.lrc.lyric.split('\n')
          arr.forEach(item => {
            let arr2 = item.split(']')
            let lineLyric = arr2[1]
            let time = arr2[0].slice(1, -1)
            let time2 = time.split(':')
            let time3 = Number(time2[0]) * 60 + Number(time2[1])
            if (lineLyric != undefined && lineLyric.length > 0) {
              this.data.lyricArr.push({ lineLyric, time: time3 })
            }
          })
          this.setData({
            lyricArr: this.data.lyricArr
          })
        }
      }
    })
  },

  //关闭弹出层
  popupClose() {
    this.setData({ popupShow: false });
  },

  //播放列表弹出层切换歌曲
  changePlaySong(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      playIndex: index,
      getWords: false
    })
    this.setData({
      musicUrl: `https://music.163.com/song/media/outer/url?id=${this.data.songsList[this.data.playIndex].id}.mp3`
    })
    audio.src = this.data.musicUrl
  },

  //切换歌曲封装
  changePlaySong2(index) {
    this.setData({
      playIndex: index
    })
    this.setData({
      musicUrl: `https://music.163.com/song/media/outer/url?id=${this.data.songsList[this.data.playIndex].id}.mp3`
    })
    audio.src = this.data.musicUrl
  },

  //播放模式
  playModeChangeSongs(clickIndex) {
    if (clickIndex == 1) {
      if (this.data.playMode == 1 || this.data.playMode == 0) {
        let index = this.data.playIndex - 1
        if (this.data.playIndex == 0) {
          index = this.data.songsList.length - 1
        }
        this.changePlaySong2(index)
      } else if (this.data.playMode == 2) {
        let index = Math.floor(Math.random() * this.data.songsList.length)
        this.changePlaySong2(index)
      }
    } else if (clickIndex == 111) {
      audio.seek(0)
    } else {
      if (this.data.playMode == 1 || this.data.playMode == 0) {
        let index = this.data.playIndex + 1
        if (this.data.playIndex == this.data.songsList.length - 1) {
          index = 0
        }
        this.changePlaySong2(index)
      } else if (this.data.playMode == 2) {
        let index = Math.floor(Math.random() * this.data.songsList.length)
        this.changePlaySong2(index)
      }
    }

  },

  //播放列表删除歌曲
  deleteList(e) {
    let index = e.currentTarget.dataset.index
    Dialog.confirm({
      title: '提醒',
      message: '确定删除吗？',
    })
      .then(() => {
        this.data.songsList.splice(index, 1)
        this.setData({
          songsList: this.data.songsList
        })
        wx.setStorageSync('songs', this.data.songsList)
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const query = wx.createSelectorQuery()
    this.data.songsList = JSON.parse(wx.getStorageSync('songs'))
    this.setData({
      musicId: options.id,
      songsList: this.data.songsList,
      playIndex: Number(options.index),
    })
    this.data.songsList.forEach(item => {
      if (typeof (item.ar) == 'string') {
      } else if (item.ar) {
        let author = ''
        item.ar.forEach(item2 => {
          author += item2.name + ','
        })
        item.ar = author.slice(0, -1)
      } else {
        item.ar = item.artists[0].name
      }
    })
    this.setData({
      songsList: this.data.songsList,
      musicUrl: `https://music.163.com/song/media/outer/url?id=${this.data.songsList[this.data.playIndex].id}.mp3`
    })
    // this.setData({
    //   musicUrl: `https://music.163.com/song/media/outer/url?id=21273745.mp3`
    // })
    audio.src = this.data.musicUrl
    audio.onCanplay(() => {
      if (!this.data.getWords) {
        this.getSongWords()
        this.setData({
          getWords: true,
          top: 0,
          iniHeight: 0,
          wordsHeight: []
        })
        this.data.timer = setTimeout(() => {
          let self = this
          let firstExe = false
          query.selectAll('#song-words-list').boundingClientRect(function (res) {
            if (!firstExe) {
              res.forEach((item, index) => {
                self.data.wordsHeight.push(item.height)
                self.setData({
                  wordsHeight: self.data.wordsHeight
                })
                if (index + 1 == self.data.lyricArr.length) {
                  firstExe = true
                  return
                }
                if (index < 5) {
                  let iniHeightArr = self.data.wordsHeight.slice(0, index)
                  iniHeightArr.forEach(item => {
                    self.data.iniHeight += item
                  })
                  self.setData({
                    iniHeight: self.data.iniHeight,
                  })
                }
              })
              
            }
          }).exec(() => {
            firstExe = true
          })
          this.data.timer = null
        }, 1000);
      }
      audio.play() // 播放
      this.setData({
        isPlay: true
      })
      audio.currentTime

      // this.data.timer = setTimeout(() => {
        audio.onTimeUpdate(() => {
          let totalTime = this.formarSongsTime(audio.duration)
          let currentTime = this.formarSongsTime(audio.currentTime)
          let duration = audio.duration
          let currentTime2 = audio.currentTime
          let persent = currentTime2 / duration
          let sliderValue = Math.floor(persent * 100)
          for (let i = 0; i < this.data.lyricArr.length; i++) {
            let beforeTime = this.data.lyricArr[i].time
            let afterTime = 0
            if (i + 1 == this.data.lyricArr.length) {
              afterTime = currentTime2 + 1
            } else {
              afterTime = this.data.lyricArr[i + 1].time
            }
            if (currentTime2 >= beforeTime && currentTime2 < afterTime) {
              let height = this.data.wordsHeight.slice(0, this.data.highLightIndex)
              let totalHeight = 0
              height.forEach(item => {
                totalHeight += item
              })
              this.setData({
                highLightIndex: i,
                top: totalHeight
              })
            }
          }
          this.setData({
            totalTime,
            currentTime,
            duration,
            sliderValue
          })
        })
      // }, 200);
      
    })
    audio.onError(() => {
      Toast({
        message: '当前歌曲没有版权,将自动播放下一首',
        position: 'center'
      })
      if (this.data.playIndex == this.data.songsList.length - 1) {
        let index = 0
        this.changePlaySong2(index)
      } else {
        let index = this.data.playIndex + 1
        this.changePlaySong2(index)
      }
    })
    audio.onEnded(() => {
      if (this.data.playMode == 1) {
        this.playModeChangeSongs(111)
      } else {
        this.playModeChangeSongs()
      }
      this.setData({
        getWords: false
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // audio.destroy()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})